package com.youth.yomapi.pdfView;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.util.Constants;
import io.ionic.starter.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;


public class PDFViewActivity extends Activity {
    private PDFView pdfView;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private TextView pageNumView;
    private String name;
    private Integer pageNum;
    private String fileUrl;
    private RelativeLayout layout;
    private boolean isVisible = true;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAndroidNativeLightStatusBar(this,true);
        setStatusBarColor(this,R.color.pdf_white);
        Bundle extras = getIntent().getExtras();
        name = extras.getString("name");
        pageNum = Integer.parseInt(extras.getString("pageNum"));
        fileUrl = extras.getString("fileUrl");
        setContentView(R.layout.activity_pdf);
        //获取动态权限
        getPermission();
        pdfView = (PDFView) findViewById(R.id.pdfView);
        pageNumView = (TextView) findViewById(R.id.pageNum);
        TextView pdfTitle = findViewById(R.id.pdfTitle);
        pdfTitle.setText(name);
        ImageButton cancel = findViewById(R.id.pdfBack);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
                finish();
            }
        });
        layout = findViewById(R.id.pdfBar);
        pdfView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout.setVisibility(isVisible ? View.GONE : View.VISIBLE);
                isVisible = !isVisible;
            }
        });
        ImageView more = findViewById(R.id.pdfMore);
        more.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                try {
                    showByOtherApp();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
        //选择pdf
        try {
            Constants.THUMBNAIL_RATIO = 1.0f;
            pdfView.fromFile(new File(new URI(fileUrl)))
    //                .pages(0, 2, 3, 4, 5); // 把0 , 2 , 3 , 4 , 5 过滤掉
                    //是否允许翻页，默认是允许翻页
                    .enableSwipe(true)
                    //pdf文档翻页是否是垂直翻页，默认是左右滑动翻页
                    .swipeHorizontal(false)
                    //
                    .enableDoubletap(true)
                    //设置默认显示第0页
                    .defaultPage(pageNum - 1)
                    //允许在当前页面上绘制一些内容，通常在屏幕中间可见。
    //                .onDraw(onDrawListener)
    //                // 允许在每一页上单独绘制一个页面。只调用可见页面
    //                .onDrawAll(onDrawListener)
                    //设置加载监听
                    .onLoad(new OnLoadCompleteListener() {
                        @Override
                        public void loadComplete(int nbPages) {
                            pageNumView.setText(pageNum +  "/");
                        }
                    })
                    //设置翻页监听
                    .onPageChange(new OnPageChangeListener() {
                        @Override
                        public void onPageChanged(int page, int pageCount) {
                            pageNum = page + 1;
                            pageNumView.setText(page + 1 + "/" + pageCount);
                        }
                    })
                    //设置页面滑动监听
//                    .onPageScroll(new OnPageScrollListener())
    //                .onError(onErrorListener)
                    // 首次提交文档后调用。
    //                .onRender(onRenderListener)
                    // 渲染风格（就像注释，颜色或表单）
                    .enableAnnotationRendering(false)
                    .password(null)
                    .scrollHandle(null)
                    // 改善低分辨率屏幕上的渲染
                    .enableAntialiasing(true)
                    // 页面间的间距。定义间距颜色，设置背景视图
                    .spacing(0)
                    .load();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    private void cancel(){
        JSONObject dataResault = new JSONObject();
        try {
            dataResault.put("pageNum", pageNum);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        PDFViewer.callbackContext.success(dataResault);
    }
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private void getPermission() {
        int hasWriteContactsPermission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(this,
                        PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }

            ActivityCompat.requestPermissions(this,
                    PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }

        while ((ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) != PackageManager.PERMISSION_GRANTED) {
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        cancel();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    /**
     * 修改状态栏颜色，支持4.4以上版本
     * @param activity
     * @param colorId
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void setStatusBarColor(Activity activity, int colorId) {
        Window window = activity.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(activity.getResources().getColor(colorId));
    }
    private static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//隐藏状态栏但不隐藏状态栏字体
            //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏，并且不显示字体
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏文字颜色为暗色

        }
    }
    private void showByOtherApp() throws URISyntaxException {
        File file = new File(new URI(fileUrl));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Context context = getApplicationContext();
        Uri path = FileProvider.getUriForFile(context, getPackageName() + ".provider", file);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(Intent.createChooser(intent, "选择以下应用打开文件"));
    }
}
